﻿using BootstrapBlazor.Components;
using BootstrapBlazorApp.Shared.Data;
using BootstrapBlazorApp.Shared.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Json;

namespace BootstrapBlazorApp.Shared.Pages
{
    public partial class CompanyInfo
    {
        [Inject]
        [NotNull]
        private IStringLocalizer<CompanyModel>? Localizer { get; set; }

        [Inject]
        [NotNull]
        private DialogService? DialogService { get; set; }

        [Inject]
        [NotNull]
        private CompanyService companyService { get; set; }

        [Inject]
        [NotNull]
        private HttpClient Http { get; set; }

        private static readonly Random random = new();
        /// <summary>
        /// 获得/设置 分页配置数据源
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] { 10 };

        private static string GetAvatarUrl(int id) => $"_content/BootstrapBlazorApp.Shared/images/avatars/150-{id}.jpg";

        private static Color GetProgressColor(int count) => count switch
        {
            >= 0 and < 10 => Color.Secondary,
            >= 10 and < 20 => Color.Danger,
            >= 20 and < 40 => Color.Warning,
            >= 40 and < 50 => Color.Info,
            >= 50 and < 70 => Color.Primary,
            _ => Color.Success
        };
        private CompanyModel Model { get; set; } = new CompanyModel()
        {
            CompanyName = "Name 1234",
            Address = "Address 1234"
        };

        [NotNull]
        private IEnumerable<CompanyModel>? Items { get; set; }

        private static readonly ConcurrentDictionary<Type, Func<IEnumerable<CompanyModel>, string, SortOrder, IEnumerable<CompanyModel>>> SortLambdaCache = new();

        private async Task<QueryData<CompanyModel>> OnQueryAsync(QueryPageOptions options)
        {
            // 此处代码实战中不可用，仅仅为演示而写防止数据全部被删除
            if (Items == null || !Items.Any())
            {
                Items = CompanyModel.GenerateCompanyModel(Localizer, 23).ToList();
            }
            //方式一
            //var result1 =await Http.GetFromJsonAsync<List<CompanyModel>>("company/all/");
            //方式二
            var result = await companyService.GetCompaniesAsync(options.SearchText ?? "");


            //var res= result.Select(x => new CompanyModel()
            //{
            //    CompanyName = Localizer["CompanyModel.CompanyName"],
            //    Phone = Localizer["CompanyModel.Phone"],
            //    Address = Localizer["CompanyModel.Address"]
            //}).ToList();
            var items = Items;
            var isSearched = false;
            // 处理高级查询
            if (options.SearchModel is CompanyModel model)
            {
                if (!string.IsNullOrEmpty(model.CompanyName))
                {
                    items = items.Where(item => item.CompanyName?.Contains(model.CompanyName, StringComparison.OrdinalIgnoreCase) ?? false);
                }

                if (!string.IsNullOrEmpty(model.Address))
                {
                    items = items.Where(item => item.Address?.Contains(model.Address, StringComparison.OrdinalIgnoreCase) ?? false);
                }

                isSearched = !string.IsNullOrEmpty(model.CompanyName) || !string.IsNullOrEmpty(model.Address);
            }

            if (options.Searchs.Any())
            {
                // 针对 SearchText 进行模糊查询
                items = items.Where(options.Searchs.GetFilterFunc<CompanyModel>(FilterLogic.Or));
            }

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<CompanyModel>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                // 外部未进行排序，内部自动进行排序处理
                var invoker = SortLambdaCache.GetOrAdd(typeof(CompanyModel), key => LambdaExtensions.GetSortLambda<CompanyModel>().Compile());
                items = invoker(items, options.SortName, options.SortOrder);
                isSorted = true;
            }

            var total = items.Count();

            return await Task.FromResult(new QueryData<CompanyModel>()
            {
                Items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                TotalCount = total,
                IsFiltered = isFiltered,
                IsSorted = isSorted,
                IsSearch = isSearched
            });
        }
        private async Task<bool> OnSaveAsync(CompanyModel item, ItemChangedType changedType)
        {
            // 增加数据演示代码
            if (changedType == ItemChangedType.Add)
            {
                await companyService.AddCompany(item);
            }
            else
            {
                await companyService.UpdateCompany(item);
            }
            return await Task.FromResult(true);
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<CompanyModel> items)
        {
            var id = items.FirstOrDefault()?.Id;
            if (id == null) return false;
            await companyService.DeleteCompany(id.Value);
            return await Task.FromResult(true);
        }

        private async Task ShowDialog()
        {
            var items = Utility.GenerateEditorItems<CompanyModel>();


            var option = new EditDialogOption<CompanyModel>()
            {
                Title = "编辑对话框",
                Model = Model,
                Items = items,
                ItemsPerRow = 2,
                RowType = RowType.Inline,
                OnCloseAsync = () =>
                {
                    return Task.CompletedTask;
                },
                OnEditAsync = async context =>
                {
                    //获取context.Model 进行保存入库
                    await companyService.AddCompany(context.Model as CompanyModel);
                    return await Task.FromResult(true);
                }
            };

            await DialogService.ShowEditDialog(option);
        }

        private async Task ShowEditDialog()
        {
            var items = Utility.GenerateEditorItems<CompanyModel>();


            var option = new EditDialogOption<CompanyModel>()
            {
                Title = "编辑对话框",
                Model = Model,
                Items = items,
                ItemsPerRow = 2,
                RowType = RowType.Inline,
                OnCloseAsync = () =>
                {
                    return Task.CompletedTask;
                },
                OnEditAsync = context =>
                {
                    return Task.FromResult(true);
                }
            };

            await DialogService.ShowEditDialog(option);
        }
    }
}
